<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
	<form onsubmit="return false;">
		UserName: <input type="text" name="userId" value="1" /> Password:<input type="text"
			id="pwd" name="password" value="1" /> <input type="button"
			value="Login" onclick="login(this.form.userId.value)" /> <br /> <input
			type="text" name="message" value="Hello, World!" /> <input
			type="button" value="Send Web Socket Data"
			onclick="send(this.form.message.value)" />
	</form>
	<div id="msg">
		
	</div>
	<script type="text/javascript">

var socket;


function login(userId){
	var pwd = $("#pwd").val();
	$.ajax({
		url:"http://localhost:8088/auth?userId="+userId+"&password="+pwd,
		type:"GET",
		dataType:"JSON",
		success:function(d){
			console.info(d);
			if(d.success){
				if (window.WebSocket) {
				    socket = new WebSocket("ws://localhost:8088/chat?token="+d.token);
				    socket.onmessage = function(event) {
				    	write("Received: " + event.data);
				    };
				    socket.onopen = function(event) {
				    	write("Web Socket opened!");
				    };
				    socket.onclose = function(event) {
				    	write("Web Socket closed.");
				    };
				} else {
				    alert("Your browser does not support Websockets. (Use Chrome)");
				}
			}else{
				alert("登录失败");
			}
			
		}
	});
}

function send(message) {
    if (!window.WebSocket) {
        return;
    }
    if (socket.readyState == WebSocket.OPEN) {
        socket.send(message);
    } else {
        alert("The socket is not open.");
    }
}

function write(message){
	$("#msg").append('<p>'+message+'</p>');
}
</script>
</body>
</html>